package com.scyshkj.university.wechat.pay;

import com.scyshkj.university.wechat.SessionKeys;
import com.scyshkj.university.wechat.utils.JacksonUtil;
import com.scyshkj.university.wechat.utils.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by 唐旭 on 2016/11/18.
 */
@Service
public class WechatLoginServiceImpl implements WechatLoginService {
    @Autowired
    private WechatProperties wechatProperties;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public boolean isLogin() {
        Object attribute = SessionUtils.getAttribute(SessionKeys.WECHAT_ACCESS_TOKEN);
        return attribute != null;
    }

    @Override
    public String getLoginUrl(HttpServletRequest request) {
        String redirectUri;

        String queryString = request.getQueryString();
        String requestURI = request.getRequestURI();
        if (!StringUtils.isEmpty(queryString)) {
            requestURI = requestURI + "?" + queryString;
        }
        String format = String.format(wechatProperties.getLoginUrl(), requestURI);

        try {
            redirectUri = URLEncoder.encode(format, "UTF-8");
        } catch (UnsupportedEncodingException var4) {
            throw new RuntimeException(var4);
        }

        return String.format(wechatProperties.getRedirectUserAuthorizeUrl(), wechatProperties.getAppid(), redirectUri, "");
    }

    @Override
    public String loginByCode(String code) {
        String s = new WechatAccessTokenParameter(wechatProperties, code).toUrlString();
        ResponseEntity<String> forEntity = restTemplate.getForEntity(wechatProperties.getAccessTokenUrl() + "?" + s, String.class);
        WechatAccessToken body = JacksonUtil.readValue(forEntity.getBody(), WechatAccessToken.class);
        if (body == null || !StringUtils.isEmpty(body.getErrmsg())) {
            return "error";
        }
        SessionUtils.setAttribute(SessionKeys.WECHAT_ACCESS_TOKEN, body);
        return null;
    }
}
